package com.lyq.pdf.pdfbox;

import org.apache.pdfbox.multipdf.Overlay;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 将多个 PDF 合并为单个 PDF
 */
public class MergePDFsExample {
    public void merge1() {
        try {
            long startTime = System.currentTimeMillis();
            String sourceFile = "D://1.pdf";
            String overlayFile = "D://2.pdf";
            String targetFile = "D://3.pdf";

            Overlay overlay = new Overlay();
            overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
            overlay.setInputPDF(PDDocument.load(new File(sourceFile)));
            overlay.setAllPagesOverlayPDF(PDDocument.load(new File(overlayFile)));

            Map<Integer, String> ovmap = new HashMap<Integer, String>();
            overlay.overlay(ovmap).save(targetFile);

            long endTime = System.currentTimeMillis();

            System.out.println("cost time : " + (endTime - startTime) );

            for (Map.Entry<Integer, String> integerStringEntry : ovmap.entrySet()) {
                System.out.println(integerStringEntry.getKey() + "," + integerStringEntry.getValue());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void merge2() {
        try {
            // load pdf files to be merged
            File file1 = new File("D://1.pdf");
            File file2 = new File("D://2.pdf");
//        File file3 = new File("/home/tk/sample_3.pdf");

            // instantiatE PDFMergerUtility class
            PDFMergerUtility pdfMerger = new PDFMergerUtility();

            // set destination file path
            pdfMerger.setDestinationFileName("D://3.pdf");

            // add all source files, to be merged, to pdfMerger
            pdfMerger.addSource(file1);
            pdfMerger.addSource(file2);
//        pdfMerger.addSource(file3);

            // merge documents
            pdfMerger.mergeDocuments(null);

            System.out.println("PDF Documents merged to a single file");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        MergePDFsExample mergePDFsExample = new MergePDFsExample();
        mergePDFsExample.merge1();
    }
}
